from django.http import HttpResponse
from django.shortcuts import render
from tfidf.search import rank, search_term, get_doc
import json

def index(request):
	query = request.GET.get('query')
	context = None
	if query:
		print("searching results ...")
		docs = rank(query)
		print("Displaying results ...")
		for doc in docs:
			print("Processing %d" % doc.id)
			if len(doc.content) > 500:
				doc.content = doc.content[:500] + " ... "
		context = {'docs': docs, 'query': query}
	return render(request, 'tfidf/home.html', context)

def show_cache(request):
	doc_id = request.GET.get('id')
	query = request.GET.get('query')
	doc = get_doc(doc_id)
	context = { 'doc' : doc, 'query': query }
	return render(request, 'tfidf/cache.html', context)

def term_autocomplete(request):
    term = request.GET.get('query')
    suggested_terms = search_term(term)
    result = {}
    result['suggestions'] = suggested_terms
    return HttpResponse(json.dumps(result))
